<template>
  <uni-popup ref="popup" type="bottom" :is-mask-click="false">
    <view class="dialog-container">
      <!-- 标题 -->
      <view class="dialog-title">巡检反馈</view>

      <!-- 表单内容 -->
      <uni-forms
        ref="formRef"
        :modelValue="formData"
        class="form-container"
        label-width="150"
      >
        <!-- 计划名称 -->
        <uni-forms-item label="巡检计划名称">
          <text class="readonly-text">{{ resave2ad }}</text>
        </uni-forms-item>

        <!-- 任务名称 -->
        <uni-forms-item label="巡检任务名称">
          <text class="readonly-text">{{ namead }}</text>
        </uni-forms-item>

        <!-- 是否异常 -->
        <uni-forms-item
          label="是否异常"
          name="isAbnormal"
          required
          :rules="[{ required: true, errorMessage: '请选择是否异常' }]"
        >
          <view class="abnormal-picker" @click="abnormalPopup.open()">
            <text v-if="formData.isAbnormal" style="margin-left: auto">
              {{
                abnormalOptions.find(
                  (item) => item.value === formData.isAbnormal
                )?.text
              }}
            </text>
            <text v-else class="placeholder" style="margin-left: auto"
              >请选择</text
            >
            <uni-icons type="arrowright" size="24" color="#d7d7da"></uni-icons>
          </view>
          <SelectPopup
            ref="abnormalPopup"
            :items="abnormalOptions"
            :value="formData.isAbnormal"
            @select="selectIsAbnormal"
          />
        </uni-forms-item>

        <!-- 时间选择 -->
        <uni-forms-item label="巡检开始时间">
          <uni-datetime-picker
            type="datetime"
            v-model="formData.startTime"
            placeholder="请选择开始时间"
          />
        </uni-forms-item>

        <uni-forms-item label="巡检结束时间">
          <uni-datetime-picker
            type="datetime"
            v-model="formData.endTime"
            placeholder="请选择结束时间"
          />
        </uni-forms-item>

        <!-- 描述 -->
        <uni-forms-item label="描述" class="textarea-desc">
          <textarea
            class="textarea"
            placeholder="请输入描述"
            v-model="formData.description"
          />
        </uni-forms-item>

        <!-- 视频上传 -->
        <uni-forms-item label="巡检视频" class="item-bg">
          <!-- 视频上传（使用默认限制） -->
          <VideoUpload @change="(files) => (formData.video = files)" />
        </uni-forms-item>

        <!-- 图片上传 -->
        <uni-forms-item label="巡检图片" class="item-bg">
          <!-- 图片上传（使用默认限制） -->
          <ImageUpload @change="(files) => (formData.images = files)" />
        </uni-forms-item>
      </uni-forms>

      <!-- 操作按钮 -->
      <view class="btn-group">
        <button class="transfer-btn" @click="close">取消</button>
        <button class="submit-btn" @click="submit">确定</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import ImageUpload from "@/components/ImageUpload/ImageUpload.vue";
import VideoUpload from "@/components/VideoUpload/VideoUpload.vue";
import api from "@/api/modules/home";

const $emit = defineEmits(["submit"]);

interface FormData {
  isAbnormal: string;
  startTime: string;
  endTime: string;
  description: string;
}

// 定义响应式变量
const popup = ref();
const formData = ref<FormData>({
  isAbnormal: "",
  startTime: "",
  endTime: "",
  description: "",
});

// 定义异常选项
const abnormalOptions = ref([
  { value: "1", text: "正常" },
  { value: "0", text: "异常" },
]);
const abnormalPopup = ref();

// 动态计算 resave2ad 和 namead
let currRow = ref<any>({});
const resave2ad = computed(() => currRow.value?.resave2 || "--");
const namead = computed(() => currRow.value?.name || "--");

// 选择是否异常
const selectIsAbnormal = (item: { value: string; text: string }) => {
  formData.value.isAbnormal = item.value;
};

// 打开弹窗
const open = (row: any) => {
  currRow.value = { ...row };
  popup.value.open();
  uni.hideTabBar();
};

// 关闭弹窗
const close = () => {
  popup.value.close();
  uni.showTabBar();
};

// 提交处理
let formRef = ref();
const submit = async () => {
  try {
    formRef.value
      .validate()
      .then(async () => {
        // 构建请求参数
        const requestData = {
          resave2: resave2ad.value,
          name: namead.value,
          resave3: formData.value.isAbnormal === "1" ? "正常" : "异常",
          start_time: formatDateTime(formData.value.startTime),
          end_time: formatDateTime(formData.value.endTime),
          description: formData.value.description,
          uuid: currRow.value?.uuid,
          attachmentList: [],
        };

        console.log("提交参数:", requestData);

        const res = await api.trueTaskUpdateById(requestData);

        if (res.code === 0) {
          uni.showToast({ title: "提交成功", icon: "success" });
          close();
          $emit("submit");
        }
      })
      .catch((err) => {});
  } catch (error) {
    console.error("提交失败", error);
    uni.showToast({
      title: error?.response?.data?.msg || "提交失败",
      icon: "none",
    });
  }
};

// 时间格式化方法
const formatDateTime = (timestamp: string) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(
    date.getDate()
  )} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(
    date.getSeconds()
  )}`;
};

const pad = (n: number) => n.toString().padStart(2, "0");

defineExpose({ open });
</script>

<style lang="scss" scoped>
.dialog-container {
  width: 100%;
  background: #fff;
  max-height: 80vh;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .dialog-title {
    font-weight: 500;
    font-size: 36rpx;
    color: #ffffff;
    font-weight: bold;
    margin-bottom: 24rpx;
    height: 85rpx;
    line-height: 85rpx !important;
    text-align: center;
    background: #5e93ff;
    border-radius: 20rpx 20rpx 0rpx 0rpx;
  }
  .uni-forms {
    padding: 0 30rpx;
    flex: 1;
    overflow: auto;
    .uni-forms-item {
      margin-bottom: 10rpx !important;
      align-items: center;
      &.item-bg {
        flex-wrap: wrap;
        :deep(.uni-forms-item__content) {
          width: 100%;
          flex: auto;
        }
        :deep(.upload-tips) {
          position: absolute;
          left: 75px;
          bottom: 0;
          top: -32px;
        }
      }
      .fault-type-picker {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10rpx 0;
        color: #666;
        font-size: 28rpx;
      }
    }
  }
  .btn-group {
    padding: 20rpx 40rpx;
  }
}

.form-container {
  :deep(.uni-forms-item__label) {
    font-size: 28rpx;
    color: #666;
  }
}

.readonly-text {
  color: #333;
  font-size: 28rpx;
}
.abnormal-picker {
  display: flex;
  align-items: center;
}
.tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 12rpx;
}

.textarea {
  width: 100%;
  height: 160rpx;
  padding: 16rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 32rpx;
  margin-top: 40rpx;

  .btn {
    padding: 16rpx 48rpx;
    border-radius: 8rpx;
    font-size: 28rpx;

    &.cancel {
      background: #f5f5f5;
      color: #666;
    }

    &.confirm {
      background: #007aff;
      color: white;
    }
  }
}
</style>
